package cmd

import (
	"fmt"
	"os"

	"hal-client/client"

	"github.com/spf13/cobra"
)

var (
	socketPath string
	halClient  *client.HALClient
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "hal-cli",
	Short: "HAL硬件抽象层CLI客户端",
	Long: `HAL CLI客户端用于与HAL服务器通信，支持各种硬件操作和系统配置。`,
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		// 初始化HAL客户端
		halClient = client.NewHALClient(socketPath)
		if err := halClient.Connect(); err != nil {
			fmt.Printf("连接HAL服务器失败: %v\n", err)
			os.Exit(1)
		}
	},
	PersistentPostRun: func(cmd *cobra.Command, args []string) {
		// 断开连接
		if halClient != nil {
			halClient.Disconnect()
		}
	},
}

// Execute adds all child commands to the root command and sets flags appropriately.
func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	rootCmd.PersistentFlags().StringVar(&socketPath, "socket", "/tmp/hal", "HAL服务器socket路径")
}